using IQIGame.Onigao.Framework;
using IQIGame.Onigao.Game;
using System;
using UnityEngine;

namespace IQIGame.Onigao.GamePlay
{
    public class UIN_CommonToggle : UIBaseNode
    {
        #region Template Generate,don't modify
        protected partial class UIB_UIN_CommonToggle
        {
            #region ObjectBinding Generate
            public IQIGame.Onigao.Framework.ExToggle toggle { protected set; get; }
            public IQIGame.Onigao.Framework.ExText title { protected set; get; }
            public virtual void InitBinding(ObjectBinding __binding)
            {
                __binding.TryGetVariableValue<IQIGame.Onigao.Framework.ExToggle>("toggle", out var __tbv0);
                this.toggle = __tbv0;
                __binding.TryGetVariableValue<IQIGame.Onigao.Framework.ExText>("title", out var __tbv1);
                this.title = __tbv1;
            }
            #endregion ObjectBinding Generate 
        }
        #endregion Template Generate,don't modify

        #region fields & properties
        private Action<int, bool> callOnValChanged = null;
        private int currIndex = 0;

        protected CanvasGroup cvsGroup { get; private set; }
        protected UIB_UIN_CommonToggle ui { get; set; }
        #endregion

        protected override void BeforeInit()
        {
            ui = new UIB_UIN_CommonToggle();
            ui.InitBinding(this.csObjBind);
        }

        protected override void OnInit()
        {
            this.ui.toggle.onValueChanged.AddListener(this.OnTogValueChanged);
            var group = this.ui.toggle.group;
            if (group != null && group.allowSwitchOff)
            {
                this.cvsGroup = this.gameObject.GetOrAdd<CanvasGroup>();
            }
        }

        protected override void OnShow()
        {

        }

        protected override void OnHide()
        {

        }

        protected virtual void OnTogValueChanged(bool isOn)
        {
            if (this.cvsGroup != null)
                this.cvsGroup.interactable = !isOn;

            this.callOnValChanged?.Invoke(this.currIndex, isOn);
        }

        protected override void OnDispose()
        {
            this.callOnValChanged = null;
        }

        public void Show(int index, string label = null)
        {
            this.Show();
            this.currIndex = index;
            if (!string.IsNullOrEmpty(label))
            {
                this.ui.title.text = label;
            }
        }

        public void SetCallOnValChanged(Action<int, bool> onValChanged)
        {
            this.callOnValChanged = onValChanged;
        }

        public void SetDefaultIsOn(bool isOn)
        {
            var _call = this.callOnValChanged;
            this.callOnValChanged = null;
            this.SetIsOn(isOn);
            this.callOnValChanged = _call;
        }

        public void SetIsOn(bool isOn)
        {
            this.ui.toggle.isOn = isOn;
        }
    }
}
